package com.ldk.admin.controller;


import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ldk.admin.factory.RegionExt;
import com.ldk.admin.factory.RegionFactory;
import com.ldk.base.framework.util.SystemUtil;
import com.ldk.framework.entity.*;
import com.ldk.framework.service.*;
import com.ldk.framework.service.impl.CompanyService;
import com.ldk.framework.service.impl.CompanyserviceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.ldk.admin.common.LigerUIGridResult;
import com.ldk.admin.common.ResponseResult;
import com.ldk.admin.constants.FORM;
import com.ldk.admin.constants.ViewMode;
import com.ldk.admin.factory.AreaExt;
import com.ldk.admin.factory.AreaFactory;
import com.ldk.base.framework.common.CustomPageable;

@Controller
@RequestMapping("/area")
public class AreaController extends BaseController {
    /**
     * 路由地址
     */
    private final String route = "area";
    /**
     * 模块名称
     */
    private final String module = "开通城市";

    @Autowired
    private IAreaService areaService;
    @Autowired
    private IRegionService regionService;
    @Autowired
    private ICompanypermitService companypermitService;

    @RequestMapping("/list")
    //public ModelAndView list(ModelMap map){
    public ModelAndView list(ModelMap map, HttpServletRequest request,
                             HttpServletResponse response) {
        //session是否过期
        this.isExpired(request, response);
        if (this.getRoleId(request) == 6) {
            setLinks(map, "", "", module + "管理", "/" + route + "/list", "", "");
        } else {
            setLinks(map, "", "", module + "管理", "/" + route + "/list", "添加" + module, "/" + route + "/add");
        }

        map.addAttribute("route", route);
        map.addAttribute("module", module);

        //操作日志
        //this.insertOplog(request,module+"管理","","","查看",this.getAdminUserName(request).toString(), Long.parseLong(this.getAdminId(request).toString()),SystemUtil.getAllSeconds());

        if (this.getRoleId(request) == 6) {
            return new ModelAndView("/area/list_sj");
        } else {
            return new ModelAndView("/area/list");
        }
    }

    @ResponseBody
    @RequestMapping("/getList")
    public LigerUIGridResult<Area> getList(@RequestParam(value = "page", required = false, defaultValue = "1") int page,
                                           @RequestParam(value = "pagesize", required = false, defaultValue = "10") int pageSize,
                                           @RequestParam(value = "searchKey", required = false, defaultValue = "") String searchKey,
                                           HttpServletRequest request) {
        int limit = pageSize;
        int offset = (page - 1) * pageSize;

        Area query = new Area();
        if (!StringUtils.isEmpty(searchKey)) {
            query.setSearchKey(searchKey);
        }
        CustomPageable pageable = new CustomPageable(offset, limit);
        Page<Area> result = areaService.selectPageList("", query, pageable);

        LigerUIGridResult<Area> grid = new LigerUIGridResult<>();
        grid.Total = result.getTotalElements();
        grid.Rows = result.getContent();

        return grid;
    }

    @ResponseBody
    @RequestMapping(value="/getTreeList",method = {RequestMethod.POST, RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE)
    public List<RegionExt> getTreeList()
    {
        Region query = new Region();
        query.setEnabled(true);

        List<Region> regions = regionService.selectList("", query);

        RegionFactory factory = new RegionFactory();
        return factory.build(regions);
    }

    /**
     * 获取指定地区下的一级地区
     * @param regionId
     * @return
     */
    @ResponseBody
    @RequestMapping(value="/getRegion",method = {RequestMethod.POST, RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseResult getRegion(@RequestParam(value="regionId",required=false,defaultValue="1") int regionId){

        ResponseResult rst = new ResponseResult();
        try{
            Region query = new Region();
            query.setParentId(regionId);

            List<Region> regions = regionService.selectList("", query);

            rst.AddOk(regions);

        }
        catch(Exception e){
            rst.AddError("获取地区失败");
        }

        return rst;

    }


    @RequestMapping("/add")
    public ModelAndView add(ModelMap map, HttpServletRequest request,
                            HttpServletResponse response) {
        //session是否过期
        this.isExpired(request, response);
        setLinks(map, module + "管理", "/" + route + "/list", "添加" + module, "/" + route + "/add", "", "");
        setForm(map, "/" + route + "/insert", null);
        map.addAttribute("route", route);
        map.addAttribute("module", module);
        map.addAttribute("regionList", getRegionList());

        Area model = new Area();
        return new ModelAndView("/area/info", "model", model);
    }

    @RequestMapping("/edit/{areaId}")
    public ModelAndView edit(@PathVariable long areaId, ModelMap map, HttpServletRequest request,
                             HttpServletResponse response) {
        //session是否过期
        this.isExpired(request, response);
        Area query = new Area();
        query.setAreaId(areaId);

        //Area model = areaService.selectByKey("", query);
        Area model = areaService.selectOne("", query);

        if (model == null) {
            return new ModelAndView("redirect:/" + route + "/list");
        }
        setLinks(map, module + "管理", "/" + route + "/list", "编辑" + module, "/" + route + "/edit/" + areaId, "", "");
        setForm(map, "/" + route + "/update", null);
        map.addAttribute("route", route);
        map.addAttribute("module", module);
        map.addAttribute("regionList", getRegionList());

        return new ModelAndView("/area/info", "model", model);
    }


    @RequestMapping("/insert")
    public ModelAndView insert(@ModelAttribute("model") Area model, RedirectAttributes redAttr,
                               ModelMap map, HttpServletRequest request,
                               HttpServletResponse response) {
        //session是否过期
        this.isExpired(request, response);
        ResponseResult rst = new ResponseResult();
        redAttr.addFlashAttribute(FORM.FROM_RESULT, rst);

        Boolean success = false;
        try {


            Area query = new Area();
            //query.setParentId(model.getParentId());
            query.setAreaName(model.getAreaName());
            query.setAreaCode(model.getAreaCode());

            long count = areaService.selectCount("", query);
            if (count > 0) {
                rst.AddError(String.format("地区名称:%s已经存在", model.getAreaName()));

                return new ModelAndView("redirect:/" + route + "/add");
            }

            if(model.getEnabled()==null){
                model.setEnabled(false);
            }
            model.setUpdateTime(SystemUtil.getAllSeconds());

            this.insertOplog(request, module, "", "", "添加:" + query.getAreaName(), this.getAdminUserName(request).toString(),
                    Long.parseLong(this.getAdminId(request).toString()), SystemUtil.getAllSeconds());

            int row = areaService.insert("", model);
            success = row > 0;

        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        if (success) {
            rst.AddOk("添加" + module + "成功");
        } else {
            rst.AddError("添加" + module + "失败");
        }

        return new ModelAndView("redirect:/" + route + "/add");
    }

    @RequestMapping("/update")
    public ModelAndView update(@ModelAttribute("model") Area model, RedirectAttributes redAttr,
                               ModelMap map, HttpServletRequest request,
                               HttpServletResponse response) {
        //session是否过期
        this.isExpired(request, response);
        ResponseResult rst = new ResponseResult();
        redAttr.addAttribute("areaId", model.getAreaId());
        redAttr.addFlashAttribute(FORM.FROM_RESULT, rst);

        Boolean success = false;
        try {

            Area query = new Area();
            query.setAreaName(model.getAreaName());
            query.setAreaCode(model.getAreaCode());

            Area area = areaService.selectOne("", query);
            if (area != null && !area.getAreaId().equals(model.getAreaId())) {
                rst.AddError(String.format("地区名称:%s已经存在", model.getAreaName()));

                return new ModelAndView("redirect:/" + route + "/edit/{model.getAreaId()}");
            }

            if(model.getEnabled()==null){
                model.setEnabled(false);
            }
            model.setUpdateTime(SystemUtil.getAllSeconds());

            this.insertOplog(request, module, "", "", "修改:" + query.getAreaName(), this.getAdminUserName(request).toString(),
                    Long.parseLong(this.getAdminId(request).toString()), SystemUtil.getAllSeconds());

            int row = areaService.updateByKey("", model);
            success = row > 0;

        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        if (success) {
            rst.AddOk("编辑" + module + "成功");
        } else {
            rst.AddError("编辑" + module + "失败");
        }

        return new ModelAndView("redirect:/" + route + "/edit/{areaId}");
    }

    /**
     * 浏览
     *
     * @param id
     * @param map
     * @return
     */
    @RequestMapping("/view/{id}")
    public ModelAndView view(@PathVariable long id, ModelMap map, HttpServletRequest request,
                             HttpServletResponse response) {
        //session是否过期
        this.isExpired(request, response);
        setViewMode(map, ViewMode.View);
        Area query = new Area();
        query.setAreaId(id);
        //Area model = areaService.selectByKey("", query);
        Area model = areaService.selectOne("", query);

        map.addAttribute("module", module);
        map.addAttribute("regionList", getRegionList());

        return new ModelAndView("/area/info", "model", model);
    }

    @ResponseBody
    @RequestMapping("/remove/{areaId}")
    public ResponseResult remove(@PathVariable long areaId, HttpServletRequest request) {

        ResponseResult rst = new ResponseResult();
        if (areaId < 1) {
            rst.AddError("删除" + module + "错误");
        }
        Area query = new Area();
        query.setAreaId(areaId);

        //操作日志
        Area area = areaService.selectOne("", query);
        this.insertOplog(request, module, "", "", "删除:" + area.getAreaName(), this.getAdminUserName(request).toString(),
                Long.parseLong(this.getAdminId(request).toString()), SystemUtil.getAllSeconds());

        //int row  = areaService.deleteByKey("", query);
        int row = areaService.delete("", query);
        if (row > 0) {
            rst.AddOk("删除" + module + "成功");
        } else {
            rst.AddError("删除" + module + "失败");
        }

        return rst;
    }

    /**
     * 获取分公司列表
     *
     * @return
     */
    private List<Companypermit> getCompanyList() {
        Companypermit query = new Companypermit();
        query.setEnabled(true);

        return companypermitService.selectList("", query);
    }


    /**
     * 获取全国行政区列表
     *
     * @return
     */
    private List<Region> getRegionList() {
        Region query = new Region();
        query.setEnabled(true);

        List<Region> regions = regionService.selectList("", query);
        return regions;
    }


}
